package com.lagou.service.impl;

import com.lagou.dao.AuthcodeDao;
import com.lagou.dubbo.service.IAuthCodeService;
import com.lagou.pojo.AuthCode;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.util.Date;

@Service
@Component
@RefreshScope
public class AuthCodeServiceImpl implements IAuthCodeService {

    @Autowired
    private AuthcodeDao authcodeDao;

    @Value("${config.code.validate.expire}")
    private int codeExpireSeconds;

    @Override
    public void createNewCode(String email, String code) {
        long createTime = System.currentTimeMillis();
        long expireTime = createTime + codeExpireSeconds * 1000;

        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        authCode.setCreatetime(new Date(createTime));
        authCode.setExpiretime(new Date(expireTime));

        authcodeDao.save(authCode);
    }

    //-1-FAIL,0-SUCCESS,1-OUTTIME
    @Override
    public int validateAuthCode(String email, String code) {
        AuthCode latest = authcodeDao.findFirstByEmailOrderByIdDesc(email);
        if (latest == null) return -1;
        if (!latest.getCode().equalsIgnoreCase(code)) return -1;

        long expireTime = latest.getExpiretime().getTime();
        if (expireTime <= System.currentTimeMillis()) return 1;

        return 0;
    }

}
